#coding=utf8
import urllib2, re, urlparse
import cmrhelper

''' pictures parser '''
'''format: var picurl="/ok-comic02/kt2/SuzumiyaHaruhi/vol_02/99770_001XXKwXuG.jpg"'''
pagenumre = re.compile(r'datas=(\d+);')
pagere = re.compile(r'(^http.*)(\?v=)\d(\*s=(\d*\b))')
picre = re.compile(r'var picurl=\"(.*?)\"')
hostre = re.compile(r'(ServerList\[\d*\]=.*?;)')
ServerList = ['']*20
HostID = 0

def getserverlist(url):
    global ServerList
    ServerList[0]="http://110.99770.com:8333/";
    url = urlparse.urljoin(url,'/haodm/dmJS/love.js')
    content = urllib2.urlopen(url).read()
    l = hostre.findall(content)
    if l:
        for item in l:
            exec(item)
        return True
    else:
        return False

def getpageurls(url,content):
    "get each url of pages"
    '''urlformat: http://dm.99770.com/Comic/1274/12066/?v=1*s=4'''
    global HostID
    pagelist = []  
    if pagenumre.findall(content)[0].isdigit():
        pagelist.append(url)
        pagenum = int(pagenumre.findall(content)[0])
        if pagere.findall(url):
            urlpre = pagere.findall(url)[0][0]
            urlmid = pagere.findall(url)[0][1]
            urltail = pagere.findall(url)[0][2]
            HostID = int(pagere.findall(url)[0][3])
            print 'hostid: ',HostID
            for i in range(2,pagenum):
                pagelist.append(urlpre + str(i) + '.htm' + urlmid + str(i) + urltail)
        return pagelist
    else:
        return None

def parsepic(url):
    content = urllib2.urlopen(url).read()
    if content:
        if picre.findall(content):
            return urlparse.urljoin(ServerList[HostID-1],picre.findall(content)[0])
    else:
        return None

def getpiclist(url,title='unamed',mylog=None):
    "parser html source and js codes to generate piclist"
    pagelist = []
    piclist = []
    content = ''
    try:
        getserverlist(url)
        content = urllib2.urlopen(url).read()
        if content:
            pagelist = getpageurls(url,content)
        for item in pagelist:
            picurl = parsepic(item)
            piclist.append([picurl,picurl,title])
        return piclist
    except:
        return None
